package demo1;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 回显服务器
 */
public class UDPEchoServe {
    private DatagramSocket serve;

    public UDPEchoServe(int port) throws SocketException {
        if(port<=1024||port>65535)
        {
            throw new BindException("端口号不合法");
        }
        serve=new DatagramSocket(port);
    }

    //服务器开始运行
    public void start() throws IOException {
        System.out.println("服务器已经启动");
        while (true) {

            DatagramPacket request=new DatagramPacket(new byte[1024],1024);
            //接受不到数据会阻塞等待
            serve.receive(request);
            //拿到数据之后需要解析
            String requestString=new String(request.getData(),0, request.getLength(),"UTF-8");
            //进行数据处理
            String responseString = process(requestString);
            //处理返回一个响应
            DatagramPacket response=new DatagramPacket(
                    responseString.getBytes("UTF-8"),0,responseString.getBytes().length,request.getSocketAddress());
            serve.send(response);
            System.out.println("request: "+requestString+" response: "+responseString +"  "
            +request.getAddress()+" "+request.getPort());
        }
    }

    private String process(String string) {
        return string;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoServe udpEchoServe=new UDPEchoServe(9999);
        udpEchoServe.start();
    }
}
